/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managed.util;

import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Danilo
 */
public class LoggedInCheck implements PhaseListener {

    @Override
    public void afterPhase(PhaseEvent event) {
        FacesContext fc = event.getFacesContext();
        boolean loginPage = false;
        try{
        loginPage = fc.getViewRoot().getViewId().lastIndexOf("login") > -1 ||  fc.getViewRoot().getViewId().lastIndexOf("register") > -1 ||  fc.getViewRoot().getViewId().lastIndexOf("forgot") > -1? true : false;
        }
        catch(Exception ex){
            loginPage = false;
        }
        if (!loginPage && !loggedIn()) {
            NavigationHandler nh = fc.getApplication().getNavigationHandler();
            nh.handleNavigation(fc, null, "logout");
        }
    }

    @Override
    public void beforePhase(PhaseEvent event) {
        FacesContext facesContext = event.getFacesContext();

        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();

        response.addHeader("Pragma", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
        response.addHeader("Cache-Control", "no-store");
        response.addHeader("Cache-Control", "must-revalidate");
        response.addHeader("Expires", "Mon, 8 Aug 2006 10:00:00 GMT");

    }

    @Override
    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }

    private boolean loggedIn() {
        if(FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("id") == null)
            return false;
        return true;
    }
}
